/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.rockville.util;

import java.util.*;
import sun.misc.BASE64Encoder;

/**
 *
 * @author Usman
 */
public class StringUtil {

    /**
     * Convert a String[] to String delimited by comma(",")
     * @param str
     * @return String
     */
    public static String Implode(String[] str) {
        return Implode(str, ",");
    }
    /**
     * Convert a String[] to String delimited by the delimiter passed
     * @param str
     * @param delimiter
     * @return String
     */
    public static String Implode(String[] str, String delimiter) {
        String implodedStr = "", temp = "";
        int len = str.length;
        int count = 1;
        for (int i = 0; i < len; i++)
        {
            temp = str[i].trim();
            if (temp.equalsIgnoreCase("") || temp == null) {}
            else  {
                if (count == 1) {
                    implodedStr = temp;
                }
                else {
                    implodedStr = implodedStr + delimiter + temp;
                }
                count++;
            }
        }
        return implodedStr;
    }
    
    /**
     * Convert String to String[] on the basis of comma(",")
     * @param toExplode
     * @return
     */
    public static String[] Explode(String toExplode) {
        return Explode(toExplode, ",");
    }    
    /**
     * Convert String to String[] on the basis of the delimiter passed
     * @param toExplode
     * @param delimiter
     * @return String[]
     */
    public static String[] Explode(String toExplode, String delimiter) {
        return toExplode.split(delimiter);
    }
    
    /**
     * Capitalize the first char of the String
     * @param s
     * @return String
     */
    public static String capitalize(String s) {
        if (s.length() == 0) return s;
        return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    }
    /**
     * Capitalize the first char of each word in the String
     * @param s
     * @return String
     */
    public static String capitalizeSentense(String s) {
        if (s.length() == 0) return s;
        String[] strExploded = s.split(" ");
        s = "";
        for (int i=0; i<strExploded.length; i++) {
            if (i == 0) {
               s += capitalize(strExploded[i]) ;
            } else {
                s += " "+ capitalize(strExploded[i]) ;
            }
        }
        // Remove unnecessary space
        return s.replaceAll("[\\s]+", " ");
    }
    
    /**
     * replace all the invalid char sequences from the string passed
     * @param strToCheck
     * @return String
     */
    public static String checkForSQLInjection(String strToCheck) {
        strToCheck = strToCheck.replaceAll("truncate ", "");
        strToCheck = strToCheck.replaceAll("select ", "");
        strToCheck = strToCheck.replaceAll("update ", "");
        strToCheck = strToCheck.replaceAll("delete ", "");
        strToCheck = strToCheck.replaceAll("insert ", "");
        strToCheck = strToCheck.replaceAll(" where ", "");
        strToCheck = strToCheck.replaceAll(" from ", "");
        strToCheck = strToCheck.replaceAll("  ", " ");
        strToCheck = strToCheck.replaceAll("\"", "");
        //strToCheck = strToCheck.replaceAll("*", "");
        strToCheck = strToCheck.replaceAll("\'", "");
        strToCheck = strToCheck.replaceAll("=", "");
        return strToCheck;
    }
    
    /**
     * Returns the maximun from the string[] passed.
     * The passed String must contain valid int values.
     * Default delimiter is comma(,)
     * @param intData
     * @return int
     */
    public static int getMaxFromString(String intData) {
        return getMaxFromString(intData, ",");
    }
    /**
     * Returns the maximun from the string[] passed based on the delimiter passed.
     * The passed String must contain valid int values.
     * @param intData
     * @param Delimiter
     * @return int
     */
    public static int getMaxFromString(String intData, String Delimiter) {
        int max = 0, temp = 0;
        String str = intData;
        String[] stra;
        
        // The following line converts String to String[]
        for (Object[] obj = {new StringTokenizer(str, Delimiter),stra=new String[(new StringTokenizer(str, Delimiter).countTokens())],new int[] {0}}; ((StringTokenizer)obj[0]).hasMoreTokens(); ((String[])obj[1])[((int[])obj[2])[0]++]=((StringTokenizer)obj[0]).nextToken()) {}
        
        for (int i=0; i<stra.length; i++) {
            temp = Integer.parseInt(stra[i]);
            if (temp > max)
                max = temp;
            //log.debug("stra["+i+"]=" + temp);
        }
        return max;
    }
    
    /**
     * Returns the maximun int value and the corresponding ID from the string[] passed.
     * passed String[] must be of the following format:
     *      str[0] = "contains ID's delimited by comma"
     *      str[1] = "contains int Values delimited by comma"
     * Default delimiter is comma(,)
     * @param str
     * @return String[]
     */
    public static String[] getMaxFromString(String[] str) {
        return getMaxFromString(str, ",");
    }
    /**
     * Returns the maximun int value and the corresponding ID from the string[] passed,
     * based on the delimiter passed.
     * passed String[] must be of the following format:
     *      str[0] = "contains ID's delimited by the delimiter passed"
     *      str[1] = "contains int Values delimited by the delimiter passed"
     * @param str
     * @param Delimiter
     * @return
     */
    public static String[] getMaxFromString(String[] str, String Delimiter) {
        int max = 0, temp = 0;
        String 
                ID = "";
        String[] strID, strNum;
        String[] strResult = {"", ""};
        
        // The following line converts String to String[]
        for (Object[] obj = {new StringTokenizer(str[1], Delimiter),strNum=new String[(new StringTokenizer(str[1], Delimiter).countTokens())],new int[] {0}}; ((StringTokenizer)obj[0]).hasMoreTokens(); ((String[])obj[1])[((int[])obj[2])[0]++]=((StringTokenizer)obj[0]).nextToken()) {}
        for (Object[] obj = {new StringTokenizer(str[0], Delimiter),strID=new String[(new StringTokenizer(str[0], Delimiter).countTokens())],new int[] {0}}; ((StringTokenizer)obj[0]).hasMoreTokens(); ((String[])obj[1])[((int[])obj[2])[0]++]=((StringTokenizer)obj[0]).nextToken()) {}
        
        for (int i=0; i<strNum.length; i++) {
            temp = Integer.parseInt(strNum[i]);
            if (temp > max) {
                max = temp;
                ID = strID[i];
            }
            //log.debug("stra["+i+"]=" + temp);
        }
        
        strResult[1] = Integer.toString(max);
        strResult[0] = ID;
        
        return strResult;
    }
    
    /**
     * <pre>Utility Function which will convert a space seperated 
     * string to a camel Style string.
     * Spaces will be removed from the resultant string.</pre>
     * @param toConvert The string to be converted.
     * @return String
     */
    public static String camelStyle(String toConvert) {
        return capitalizeSentense(toConvert).replaceAll(" ", "");
    }
    
    /**
     * <pre>Utility Function which will check weather 
     * a "value" exists in the "list" or not.</pre>
     * @param list
     * @param value
     * @return
     */
    public static boolean isInList(String[] list, String value) {
        for(int i=0; i < list.length; i++) {
            if (list[i].equalsIgnoreCase(value))
                return true;
        }
        return false;
    }
    
    /**
     * <pre>
     * Converts a string to a unicode string.
     * Allows the browser to display other languages aswell.</pre>
     * @param strToConvert
     * @return
     */
    public static String toUnicode(String strToConvert) {
        String temp = "";
        char[] charr;
        
        charr = strToConvert.toCharArray();
        
        for (int j = 0; j < charr.length; j++) {
            int c = (int) charr[j];
            if (c > 250) {
                temp = temp + "&#" + Integer.toString(c) + ";";
            } else {
                temp += charr[j];
            }
        }
        
        return temp;
    }
    
    /**
     * <pre>
     * Appends a String to the end of passed Sting[]
     * </pre>
     * @param strSource
     * @param strToAdd
     */
    public static String[] append(String[] strSource, String strToAdd) {
        int org_size = strSource.length;
        String[] temp = new String[org_size + 1];
        
        for(int i = 0; i < org_size; i++) {
            temp[i] = strSource[i];
        }
        
        temp[org_size] = strToAdd;
        //strSource = temp;
        return temp;
    }
    
    /**
     * <pre>
     * Converts the String passed to it Hex 
     * seperated by space as delimiter.
     * </pre>
     * @param toConvert
     * @return
     */
    public static String toHex(String toConvert) {
        return toHex(toConvert, " ");
    }
    /**
     * <pre>
     * Converts the String passed to it Hex 
     * seperated by the delimiter passed.
     * </pre>
     * @param toConvert
     * @param Delimiter
     * @return
     */
    public static String toHex(String toConvert, String Delimiter) {
        StringBuffer buffer = new StringBuffer();
        int intValue;
        for (int x = 0; x < toConvert.length(); x++) {
            int cursor = 0;
            intValue = toConvert.charAt(x);
            String binaryChar = new String(Integer.toBinaryString(toConvert.charAt(x)));
            for (int i = 0; i < binaryChar.length(); i++) {
                if (binaryChar.charAt(i) == '1') {
                    cursor += 1;
                }
            }
            if ((cursor % 2) > 0) {
                intValue += 128;
            }
            buffer.append(Integer.toHexString(intValue) + Delimiter);
        }
        return buffer.toString();
    }
    public static String encryptString(String msisdnStr, String key) {
		long msisdn = 0;
    	try {
			msisdn = Long.parseLong(msisdnStr);
		} catch(Exception e) {
			return "";
		}
		try {
	    	int asciisum = 0;
			for (int i = 0; i < key.length(); ++i) {
				char c = key.charAt(i);
				int j = (int) c;
				asciisum += j;
			}
			String ciphertext = String.valueOf(msisdn - asciisum);
	
			// StringEncrypter se = new StringEncrypter("DES");
			// String dec = se.encrypt(ciphertext);
			// System.out.println("Encrpt " + dec);
			// System.out.println("Decrypt " + se.decrypt(dec));
	//		System.out.println("Input string " + ciphertext);
			return new BASE64Encoder().encode(ciphertext.getBytes());
		} catch(Exception e) {
			return "";
		}			
    }
    
}
